﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; 
using System;
using System.Data;
using System.Data.SqlClient;
using XKPlatform.Common;

namespace PPLess.Controllers
{
    public class FormController : Controller
    {
        #region 表单模板

        #region 获取表单模板列表
        public JsonResult getFormList(Search search, string role)
        {
            try
            {
                var fields = QuerySuite.GetTableFieldsSql<tblForm>(new string[] { "RecordStatus", "ModifiedBy", "ModifiedOn", "FormConfig", "FormFields" });

                QuerySuite querySuite = new QuerySuite(@"(select a.*,isnull(b.UserName,a.CreatedBy) CreatedByName,c.MemberName FormGroupName from tblForm a 
left join SysUser b on a.CreatedBy=b.UserNo and b.RecordStatus=0 and b.Org=@Org
left join SysDictionary c on a.FormGroupID=c.DictionaryID and c.Org=@Org
where a.RecordStatus=0 and a.Org=@Org) t", fields+ ",CreatedByName,FormGroupName", search);

                if (role == "1")
                {
                    if (!SSOClient.IsAdmin && !SSOClient.IsDev && !SSOClient.IsAreaAdmin)
                        querySuite.AddParam(" and (CreatedBy=@UserNo or  EXISTS (select 1 from SysDictionary where DictionaryID=t.FormGroupID and Org=@Org and isnull(Remarks,'')!='' and ','+isnull(Remarks,'')+',' like '%,'+ @UserNo+',%'))", new SqlParameter("@UserNo", SSOClient.UserNo));
                }
                if (role == "2")
                {
                    querySuite.AddFilter(" and State>1");
                    if (!SSOClient.IsAdmin && !SSOClient.IsDev && !SSOClient.IsAreaAdmin)
                        querySuite.AddParam(" and EXISTS (select 1 from SysDictionary where DictionaryID=t.FormGroupID and Org=@Org and isnull(Remarks,'')!='' and ','+isnull(Remarks,'')+',' like '%,'+ @UserNo+',%')", new SqlParameter("@UserNo", SSOClient.UserNo));
                }

                querySuite.AddParam("Org", SSOClient.Org);



                    DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds)});
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 获取表单模板下拉列表
        public JsonResult getFormSelect(Search search)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblForm where RecordStatus=0 and State=3", "FormID,FormName,FormNo", search);
                querySuite.AddParam("Org","=", SSOClient.Org);

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 保存表单模板
        public JsonResult saveForm(tblForm model, string action)
        {
            try
            {
                if (string.IsNullOrEmpty(SSOClient.Org))
                    return Json(new { code = 9, msg = "当前用户无区域划分，无法执行保存" });

                tblForm oldModel = null;
                if (action == "copy")
                {
                    QuerySuite querySuite1 = new QuerySuite("tblForm where  FormID=@FormID  ");
                    querySuite1.AddParam("FormID", model.FormID);
                    oldModel = ModelHelper<tblForm>.ConvertToModel(SqlHelper.Query(querySuite1.SelectSql, querySuite1.Params).Tables[0]);
                    model.FormID = new Guid();
                }
                QuerySuite querySuite = new QuerySuite("tblForm where  FormID!=@FormID and FormNo=@FormNo");
                querySuite.AddParam("FormID", model.FormID);
                querySuite.AddParam("FormNo", model.FormNo);
                querySuite.AddParam("Org","=",SSOClient.Org);
                if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
                    return Json(new { code = 1, msg = "模板编号已存在。" });

                if (model.FormConfig!=null && model.State <= 1)
                    model.State = 1;

                if (model.FormID == new Guid())
                {
                    model.FormID = Guid.NewGuid();
                    model.CreatedOn = DateTime.Now;
                    model.CreatedBy = SSOClient.UserNo;
                    model.RecordStatus = false;
                    model.Org = SSOClient.Org;
                    model.State = 0;
                    model.IsPublic = 0;
                    model.ImportBatch = 0; 
                    if (action == "copy")
                    {
                        model.State = 1;
                        model.FormConfig = oldModel.FormConfig;
                        model.FormFields = oldModel.FormFields;
                    }
                    SqlHelper.InsertSql(model);
                }
                else
                {
                    model.ModifiedBy = SSOClient.UserNo;
                    model.ModifiedOn = DateTime.Now;
                    SqlHelper.UpdateSql(model, "FormID", new string[] { "FormNo", "FormConfig", "FormFields", "CreatedOn", "CreatedBy", "RecordStatus", "State", "IsPublic", "Org", "ImportBatch" });
                }

                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 保存表单模板配置
        public JsonResult saveFormConfig(tblForm model)
        {
            try
            {
                if (string.IsNullOrEmpty(SSOClient.Org))
                    return Json(new { code = 9, msg = "当前用户无区域划分，无法执行保存" });

                QuerySuite querySuite = new QuerySuite("tblForm");
                querySuite.AddParam("RecordStatus", "=", 0);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                querySuite.AddParam("FormID", "=", model.FormID);
                querySuite.AddParam("FormConfig", model.FormConfig);
                querySuite.AddParam("FormFields", model.FormFields);
                SqlHelper.ExecuteSql("update tblForm set FormConfig=@FormConfig,FormFields=@FormFields from " + querySuite.FromSql, querySuite.Params);

                querySuite.AddParam("State", "=", 0);
                SqlHelper.ExecuteSql("update tblForm set State=1 from " + querySuite.FromSql, querySuite.Params);

                return Json(new { code = 0 });

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 删除表单模板
        public JsonResult delForm(string ids)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblForm");//where RecordStatus=0 and isnull(State,0)!=3
                querySuite.AddParam("FormID", "inid", ids);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

                SqlHelper.ExecuteSql(@"
delete t from tblForm t where RecordStatus<>0
delete t from tblTask t where not EXISTS (select 1 from tblForm b where t.FormNo=b.FormNo and t.Org=b.Org)
delete t from tblTaskFill t where not EXISTS (select 1 from tblForm b where t.FormNo=b.FormNo and t.Org=b.Org)
delete t from tblTaskUser t where not EXISTS (select 1 from tblTask b where t.TaskNo=b.TaskNo and t.Org=b.Org)");

                //querySuite = new QuerySuite("tblForm where RecordStatus=0 and State=3");
                //querySuite.AddParam("FormID", "inid", ids);
                //querySuite.AddParam("Org", "=", SSOClient.Org);
                //querySuite.AddParam("ModifiedOn", DateTime.Now);
                //SqlHelper.ExecuteSql("update tblForm set RecordStatus=1,ModifiedOn=@ModifiedOn  from " + querySuite.FromSql, querySuite.Params);

                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 获取表单
        public JsonResult getFormInfo(Guid? dataId)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblForm");
                querySuite.AddParam("FormID", "=", dataId);
                tblForm model = ModelHelper<tblForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

                if (model.KPIFormID.HasValue)
                {
                    querySuite = new QuerySuite("SysForm");
                    querySuite.AddParam("FormID", "=", model.KPIFormID);
                    SysForm kpiModel = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
                    return Json(new { code = 0, data = new { model.FormID, model.FormNo, model.FormName, model.FormConfig, KPIFormConfig = kpiModel.tempForm } });
                }

                return Json(new { code = 0, data = new { model.FormID, model.FormNo, model.FormName, model.FormConfig } });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        public JsonResult getKpiFormInfo(Guid? dataId)
        {
            try
            {
                QuerySuite querySuite = querySuite = new QuerySuite("SysForm");
                querySuite.AddParam("FormID", "=", dataId);
                SysForm model = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
                return Json(new { code = 0, data = new { model.FormID, model.FormNo, model.FormName, model.NextFormID, model.tempForm } });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        public JsonResult getFormFields(Guid? dataId)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblForm");
                querySuite.AddParam("FormID", "=", dataId);
                tblForm model = ModelHelper<tblForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

                if (model.KPIFormID.HasValue)
                {
                    querySuite = new QuerySuite("SysForm");
                    querySuite.AddParam("FormID", "=", model.KPIFormID);
                    SysForm kpiModel = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
                    return Json(new { code = 0, data = new { model.FormFields, KPIFormFields = kpiModel.FormFields } });
                }

                return Json(new { code = 0, data = new { model.FormFields } });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 修改表单状态
        public JsonResult updateFormState(int State,Guid id)
        {
            try
            {
                QuerySuite  querySuite = new QuerySuite("tblForm ");
                querySuite.AddParam("State", State);
                querySuite.AddParam("FormID", id);
                querySuite.AddParam("ModifiedOn", DateTime.Now);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                SqlHelper.ExecuteSql("update tblForm set ModifiedOn=@ModifiedOn,State=@State  where FormID=@FormID ",  querySuite.Params);
                
                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #endregion

        #region 模板分组

        #region 获取模板分组列表
        public JsonResult getSysFormGroupConfigList(Search search)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite(@"SysDictionary a where Type='data-params' and ParentType='forms-group-config' and Org=@Org", "*,stuff((select ','+UserName from SysUser where ','+isnull(a.Remarks,'')+',' like '%,'+ UserNo+',%' and Org=@Org ORDER BY UserNo for xml path('')),1,1,'') UserNames", search);
                querySuite.AddParam("Org", SSOClient.Org);
                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 });
            }
        }
        #endregion

        #region 获取模板分组用户列表
        public JsonResult getFormGroupUserList(Search search, Guid DictionaryID)
        {
            try
            {

                QuerySuite querySuite = new QuerySuite(@"(select a.* from SysUser a,SysDictionary b where a.Org=@Org and b.Org=@Org and isnull(b.Remarks,'')!='' and ','+isnull(b.Remarks,'')+',' like '%,'+ a.UserNo+',%' and isnull(a.UserNo,'')!='' and a.RecordStatus=0 and b.DictionaryID=@DictionaryID)t", "UserID,UserName,UserNo", search);
                querySuite.AddParam("DictionaryID", DictionaryID);
                querySuite.AddParam("Org", SSOClient.Org);

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return  Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code =-1 } );
            }
        }
        #endregion

        #region 获取任务待选用户
        public JsonResult getFormGroupSelectUserList(Search search, Guid DictionaryID)
        {
            try
            {

                QuerySuite querySuite = new QuerySuite(string.Format(@"(select distinct a.*,b.DepartmentName,b.DepartmentFullName,c.PostName
                                                            from SysUser a left join SysDepartment b on a.DepartmentNo = b.DepartmentNo and b.RecordStatus = 0 and b.Org=@Org
left join SysPost c on a.PostNo = c.PostNo and c.RecordStatus = 0 and c.Org=@Org
where not EXISTS (select 1 from SysDictionary where Org=@Org and ','+isnull(Remarks,'')+',' like '%,'+ a.UserNo+',%' and DictionaryID=@DictionaryID)
                                                            and a.RecordStatus = 0 and a.Org=@Org) t"), search);

                querySuite.AddParam("DictionaryID", DictionaryID);
                querySuite.AddParam("Org", SSOClient.Org);
                //if (!SSOClient.IsAdmin())
                //    querySuite.AddParam(" and EXISTS (select 1 from dbo.getFactoryDepartmentUser(@RootDepartmentNo,@UserDepartmentNo) where t.UserNo=UserNo)", new SqlParameter[] {
                //        new SqlParameter("@RootDepartmentNo",CacheHelper.getDictionaryCache("SysFactoryDepartmentParentNo")),
                //        new SqlParameter("@UserDepartmentNo",SSOClient.DepartmentNo)
                //    });

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 });
            }
        }
        #endregion

        #region 添加模板分组用户
        public JsonResult addFormGrpupUser(Guid DictionaryID, string UserNos)
        {

            try
            {
                QuerySuite querySuite1 = new QuerySuite("SysDictionary where DictionaryID=@DictionaryID");
                querySuite1.AddParam("DictionaryID", DictionaryID);
                SysDictionary model = ModelHelper<SysDictionary>.ConvertToModel(SqlHelper.Query(querySuite1.SelectSql, querySuite1.Params).Tables[0]);
                
                if (model != null && model.Remarks != null && model.Remarks != "")
                {
                    var array = UserNos.Split(',');
                    foreach (var item in array)
                    {
                        if (model.Remarks.IndexOf(item) == -1)
                            model.Remarks += (',' + item);

                    }
                    model.Remarks = model.Remarks;
                }
                else
                    model.Remarks = UserNos;

                QuerySuite querySuite = new QuerySuite("SysDictionary");
                querySuite.AddParam("DictionaryID", "=", model.DictionaryID);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                querySuite.AddParam("Remarks", model.Remarks);
                querySuite.AddParam("ModifiedOn", DateTime.Now);

                SqlHelper.ExecuteSql("update SysDictionary set ModifiedBy='" + SSOClient.UserNo + "',ModifiedOn=@ModifiedOn,Remarks=@Remarks from " + querySuite.FromSql, querySuite.Params);
                return Json(new { code = 0 } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 } );
            }

        }
        #endregion

        #region 删除模板分组用户
        public JsonResult delFormGroupUser(Guid DictionaryID, string UserNos)
        {
            try
            {
                var arry = UserNos.Split(',');
                for (int i = 0; i < arry.Length; i++)
                {
                    QuerySuite querySuite = new QuerySuite("SysDictionary t");
                    querySuite.AddParam("t.Remarks", "include", arry[i]);
                    querySuite.AddParam("t.DictionaryID", "=", DictionaryID);
                    querySuite.AddParam("t.Org", "=", SSOClient.Org);
                    SqlHelper.ExecuteSql("update t set t.Remarks=replace(replace(replace(t.Remarks,@S_t_Remarks+',',''),','+@S_t_Remarks,''),@S_t_Remarks,'') from " + querySuite.FromSql, querySuite.Params);
                }

                return Json(new { code = 0 } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 } );
            }

        }
        #endregion

        #endregion

        #region 非常规任务

        #region 获取非常规任务列表
        public JsonResult getTaskList(Search search)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite(@"(select distinct a.*,b.FormID,b.FormName,c.UserName from tblTask a
                    join tblForm b on a.FormNo=b.FormNo and b.RecordStatus=0 and b.Org=@Org
left join SysUser c on a.CreatedBy=c.UserNo and c.RecordStatus=0 and c.Org=@Org
                    where a.RecordStatus=0 and a.Org=@Org and a.CreatedBy=@CreatedBy) t", search);
                querySuite.AddParam("Org", SSOClient.Org);
                querySuite.AddParam("CreatedBy", SSOClient.UserNo);
                //if (!SSOClient.IsAdmin())
                //    querySuite.AddParam(" and EXISTS (select 1 from dbo.getChildDepartment(@UserDepartmentNo) where t.DepartmentNo=DepartmentNo)", new SqlParameter("@UserDepartmentNo", SSOClient.DepartmentNo));

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 });
            }
        }
        #endregion

        #region 删除非常规任务
        public JsonResult delTask(string ids)
        {
            try
            {
                //QuerySuite querySuite = new QuerySuite("tblTaskUser where Org=@Org");
                //querySuite.AddParam(" and TaskNo in (select TaskNo from tblTask where Org=@Org and State=0 and ','+@TaskID+',' like ',%'+cast(TaskID as nvarchar(36))+'%,')", new SqlParameter("@TaskID", ids));

                //querySuite.AddParam("Org",  SSOClient.Org);
                //SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

                QuerySuite querySuite = new QuerySuite("tblTask");
                querySuite.AddParam("TaskID", "inid", ids);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

                //querySuite = new QuerySuite("tblTask where RecordStatus=0 and State>0");
                //querySuite.AddParam("TaskID", "inid", ids);
                //querySuite.AddParam("Org", "=", SSOClient.Org);
                //SqlHelper.ExecuteSql("update tblTask set RecordStatus=1 from " + querySuite.FromSql, querySuite.Params);

                SqlHelper.ExecuteSql(@"
delete tblTask where RecordStatus<>0
delete t from tblTaskFill t where not EXISTS (select 1 from tblTask b where t.TaskID=b.TaskID and t.Org=b.Org)
delete t from tblTaskUser t where not EXISTS (select 1 from tblTask b where t.TaskNo=b.TaskNo and t.Org=b.Org)");

                return Json(new { code = 0 } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 } );
            }
        }
        #endregion

        #region 保存非常规任务
        public JsonResult saveTask(tblTask model)
        {
            try
            {
                if (string.IsNullOrEmpty(SSOClient.Org))
                    return Json(new { code = 9, msg = "当前用户无区域划分，无法执行保存" });

                QuerySuite querySuite = new QuerySuite("tblTask where  TaskID!=@TaskID and TaskNo=@TaskNo");
                querySuite.AddParam("TaskID", model.TaskID);
                querySuite.AddParam("TaskNo", model.TaskNo);
                querySuite.AddParam("Org", "=",SSOClient.Org);
                if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
                    return Json(new { code = 1, msg = "任务编号已存在。" });

                if (model.TaskID == new Guid())
                {
                    model.TaskID = Guid.NewGuid(); 
                    model.State = 0;
                    model.CreatedOn = DateTime.Now;
                    model.CreatedBy = SSOClient.UserNo;
                    model.Org = SSOClient.Org;
                    model.RecordStatus = false;
                    model.IsPublic = 0;
                    model.ImportBatch = 0;
                    SqlHelper.InsertSql(model);
                }
                else
                {
                    model.ModifiedBy = SSOClient.UserNo;
                    model.ModifiedOn = DateTime.Now;
                    SqlHelper.UpdateSql(model, "TaskID", new string[] { "TaskNo", "CreatedOn", "CreatedBy", "RecordStatus", "ImportBatch", "State", "Org" });
                }


                return Json(new { code = 0,updateData = model });

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 } );
            }
        }
        #endregion

        #region 停用非常规任务
        public JsonResult endTask(string ids)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTask where RecordStatus=0");
                querySuite.AddParam("TaskID", "inid", ids);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                SqlHelper.ExecuteSql("update tblTask set State=2 from " + querySuite.FromSql, querySuite.Params);

                return Json(new { code = 0 } );

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 } );
            }
        }
        #endregion

        #region 启用非常规任务
        public JsonResult startTask(string ids)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTask where RecordStatus=0");
                querySuite.AddParam("TaskID", "inid", ids);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                querySuite.AddParam("ModifiedOn", DateTime.Now);
                SqlHelper.ExecuteSql("update tblTask set State=1,ModifiedOn=@ModifiedOn from " + querySuite.FromSql, querySuite.Params);

                return Json(new { code = 0 } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 } );
            }
        }
        #endregion

        #region 公开不公开任务
        public JsonResult publicTask(string ids,int ispublic)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTask where RecordStatus=0");
                querySuite.AddParam("Org", "=", SSOClient.Org);
                querySuite.AddParam("TaskID", "inid", ids);
                querySuite.AddParam("ModifiedOn", DateTime.Now);
                if (ispublic == 1)
                {
                    querySuite.AddParam("IsPublic", 1);
                }
                else
                {
                    querySuite.AddParam("IsPublic", 0);
                } 
                SqlHelper.ExecuteSql("update tblTask set IsPublic=@IsPublic,ModifiedOn=@ModifiedOn from " + querySuite.FromSql, querySuite.Params);

                return Json(new { code = 0 } );
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #endregion

        #region 任务用户

        #region 获取任务待选用户
        public JsonResult getTaskUserSelectList(Search search, string TaskNo)
        {
            try
            {

                QuerySuite querySuite = new QuerySuite(string.Format(@"(select distinct a.*,b.DepartmentName,b.DepartmentFullName,c.PostName
                                                            from SysUser a left join SysDepartment b on a.DepartmentNo = b.DepartmentNo and b.RecordStatus = 0  and b.Org=@Org
left join SysPost c on a.PostNo = c.PostNo and c.RecordStatus = 0  and c.Org=@Org
where not EXISTS (select 1 from tblTaskUser where RecordStatus=0 and TaskNo=@TaskNo and UserNo=a.UserNo and a.Org=Org )
                                                            and a.RecordStatus = 0 and a.Org=@Org) t"), search);

                querySuite.AddParam("TaskNo", TaskNo);

                    querySuite.AddParam("Org", SSOClient.Org);

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 获取任务用户列表
        public JsonResult getTaskUserList(Search search, string TaskNo)
        {
            try
            {

                QuerySuite querySuite = new QuerySuite(@"(select a.* from SysUser a,tblTaskUser b where b.UserNo = a.UserNo and a.RecordStatus=0 and b.RecordStatus=0 and a.Org=@Org and b.Org=@Org and b.TaskNo=@TaskNo)t", "UserID,UserName,UserNo", search);
                querySuite.AddParam("TaskNo", TaskNo);
                querySuite.AddParam("Org", SSOClient.Org);
                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 删除任务用户
        public JsonResult delTaskUser(string TaskNo, string UserNos)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTaskUser");
                querySuite.AddParam("UserNo", "inchar", UserNos);
                querySuite.AddParam("TaskNo", "=", TaskNo);
                querySuite.AddParam("Org", "=", SSOClient.Org);
                SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = 1 });
            }
        }
        #endregion

        #region 添加任务用户
        public JsonResult addTaskUser(string TaskNo, string UserNos)
        {
            try
            {

                SqlHelper.ExecuteSql(@"insert into tblTaskUser (TaskNo,UserNo,RecordStatus,Org) select @TaskNo,UserNo,0,@Org from SysUser a where Org=@Org and RecordStatus=0 and ','+@UserNo+',' like '%,'+UserNo+',%' 
                    and not EXISTS(select 1 from tblTaskUser where RecordStatus=0 and TaskNo=@TaskNo and UserNo=a.UserNo and Org=@Org)",
                    new SqlParameter[] { new SqlParameter("@TaskNo", TaskNo), new SqlParameter("@UserNo", UserNos), new SqlParameter("@Org", SSOClient.Org) });


                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 导入任务用户
        public JsonResult importTaskUser(string datas,string TaskNo)
        {
            if (string.IsNullOrEmpty(SSOClient.Org))
                return Json(new { code = 9, msg = "当前用户无区域划分，无法执行导入" });
            var number = new Random().Next(10000, 99999999);
            try
            {

                DataTable dt = JsonHelper.ToDataTable<tblTaskUser>(datas);
             
                foreach (DataRow dr in dt.Rows) { 
                
                    dr["ImportBatch"] = number;
                    dr["RecordStatus"] = false;
                    dr["TaskNo"] = TaskNo;
    
                    dr["CreatedBy"] = SSOClient.UserNo;
                    dr["CreatedOn"] = DateTime.Now;
                    dr["Org"] = SSOClient.Org; 
                }

                SqlHelper.BatchInsert(dt, "tblTaskUser");

                //查询验证不通过的临时数据
                var table = SqlHelper.Query(@"
             delete tblTaskUser where (ImportBatch not in (0,@ImportBatch) or RecordStatus<>0) and Org=@Org
                    select userno,'用户不存在,' ErrMsg from tblTaskUser where ImportBatch=@ImportBatch  and Org=@Org and isnull(userno,'')!='' and userno not in(select userno from sysuser where RecordStatus=0  and Org=@Org) 
                     ", new SqlParameter("@ImportBatch", number), new SqlParameter("@Org", SSOClient.Org)).Tables[0];
                if (table.Rows.Count == 0)
                {
                    //更新已存在数据
                    SqlHelper.ExecuteSql(@"

                        delete a from tblTaskUser a,tblTaskUser b  where a.ImportBatch<>@ImportBatch and a.Org=@Org and a.userno=b.userno and a.TaskNo=b.TaskNo                           
 
                        update tblTaskUser set  ImportBatch=0,RecordStatus=0    where  ImportBatch=@ImportBatch  and  Org=@Org",
                        new SqlParameter("@ImportBatch", number), new SqlParameter("@Org", SSOClient.Org));
                }
                else
                {
                    //验证失败，返回本次导入数据
                    table = SqlHelper.Query(@"
                        select a.*,isnull(b.ErrMsg,'')+isnull(c.ErrMsg,'')+isnull(d.ErrMsg,'') ErrMsg from tblTaskUser a
                        left join (  select userno,'用户不存在,' ErrMsg from tblTaskUser where ImportBatch=@ImportBatch  and Org=@Org and isnull(userno,'')!='' and userno not in(select userno from sysuser where RecordStatus=0  and Org=@Org)) b on a.userno=b.userno
                        
                        where ImportBatch=@ImportBatch and Org=@Org order by ErrMsg desc",
                        new SqlParameter("@ImportBatch", number), new SqlParameter("@Org", SSOClient.Org)).Tables[0];
                    //删除本次导入临时数据
                    SqlHelper.ExecuteSql("delete tblTaskUser where ImportBatch=@ImportBatch  and Org=@Org",
                        new SqlParameter("@ImportBatch", number), new SqlParameter("@Org", SSOClient.Org));

                    return Json(new { code = 1, data = QuerySuite.ToDictionary(table) });
                }

                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                SqlHelper.ExecuteSql("delete tblTaskUser where ImportBatch=@ImportBatch  and Org=@Org",
                    new SqlParameter("@ImportBatch", number), new SqlParameter("@Org", SSOClient.Org));
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #endregion

        #region 非常规任务填报

        #region 获取非常规任务填报
        public JsonResult getTaskFillList(Search search, Guid? TaskID)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTaskFill a left join SysUser c on a.InvalidUserNo=c.UserNo and c.Org=@Org join tblTask b on a.TaskID = b.TaskID and b.Org=@Org where a.Org=@Org ", "a.*,b.TaskName,c.UserName", search);
                querySuite.AddParam("a.TaskID", "=", TaskID);
                querySuite.AddParam("Org", SSOClient.Org);
                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 作废非常规任务填报
        public JsonResult InvalidTaskFill(tblTaskFill model)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTaskFill where  TaskFillID=@TaskFillID  ");
                querySuite.AddParam("TaskFillID", model.TaskFillID);
                querySuite.AddParam("Org", "=",SSOClient.Org);
                tblTaskFill oldModel = ModelHelper<tblTaskFill>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

                oldModel.InvalidDate = DateTime.Now;
                oldModel.InvalidReason = model.InvalidReason;
                oldModel.InvalidUserNo = SSOClient.UserNo;
                oldModel.IsInvalid = 1;
                SqlHelper.UpdateSql(oldModel, "TaskFillID");

                return Json(new { code = 0 });

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 获取表单任务信息
        [AllowAnonymous]
        public JsonResult getTaskFormInfo(Guid? TaskID)
        {
            try
            {
                QuerySuite querySuite = new QuerySuite("tblTask where RecordStatus=0");
                //querySuite.AddParam("Org", "=", SSOClient.Org);
                querySuite.AddParam("TaskID", "=", TaskID);

                //if (!SSOClient.IsDev&&!SSOClient.IsAdmin)
                //{
                //    if (SSOClient.IsManage)
                //        querySuite.AddParam(" and (IsPublic=1 or EXISTS (select 1 from dbo.getChildDepartment(@UserDepartmentNo) where t.DepartmentNo=DepartmentNo) or EXISTS (select 1 from tblTaskUser where t.TaskNo=TaskNo and UserNo=@UserNo))"
                //            , new SqlParameter[] { new SqlParameter("@UserDepartmentNo", SSOClient.DepartmentNo), new SqlParameter("@UserNo", SSOClient.UserNo) });
                //    else
                //        querySuite.AddParam(" and (IsPublic=1 or EXISTS (select 1 from tblTaskUser where t.TaskNo=TaskNo and UserNo=@UserNo))", new SqlParameter("@UserNo", SSOClient.UserNo));

                //}

                if(!SSOClient.IsLogin)
                    return Json(new { code = 3, msg = "无权访问该表单。" });

                tblTask model = ModelHelper<tblTask>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

                if (model==null)
                    return Json(new { code = 1, msg = "无权访问该表单。",data=new { model.TaskID,model.FormNo,model.TaskName} });
                if (model.State != 1)
                    return Json(new { code = 2, msg = "当前表单不可用。" });

                querySuite = new QuerySuite("tblForm");
                querySuite.AddParam("FormNo", "=", model.FormNo);
                //querySuite.AddParam("Org", "=", SSOClient.Org);
                tblForm formModel = ModelHelper<tblForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

                if (formModel.KPIFormID.HasValue)
                {
                    querySuite = new QuerySuite("SysForm");
                    querySuite.AddParam("FormID", "=", formModel.KPIFormID);
                    SysForm kpiModel = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
                    return Json(new { code = 0, data = new {Title=model.TaskName, formModel.FormID, formModel.WaitTime, formModel.FormNo, formModel.FormConfig, KPIFormConfig = kpiModel.tempForm,KpiFormID = kpiModel.FormID } });
                }

                return Json(new { code = 0, data = new { Title = model.TaskName, formModel.FormID, formModel.WaitTime, formModel.FormNo, formModel.FormConfig } });

            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 表单填报
        public JsonResult saveTaskFill(tblTaskFill model)
        {
            try
            {
                model.TaskFillID = Guid.NewGuid();
                model.FillTime = DateTime.Now;
                model.FillUserNo = SSOClient.UserNo;
                model.FillUserName = SSOClient.User.UserName;
                model.Org = SSOClient.Org;
                SqlHelper.InsertSql(model);

                return Json(new { code = 0 });
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(e);
                return Json(new { code = -1 });
            }
        }
        #endregion

        #endregion
    }
}
